/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
'use strict';

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView,
  Dimensions,
  Navigator,
  Alert,
  ListView,
  TouchableOpacity,
  Image,
  RefreshControl,
  AsyncStorage,
} from 'react-native';

import Carousel from 'react-native-looped-carousel';
import Grid from 'react-native-grid-component';
import CacheableImage from 'react-native-cacheable-image'
import styles1 from './styles/Pager.style';
import { colors } from './styles/Pager.style';

var Header = require("./Component/Header");
var net = require("./net/NetUitl");
var _navigator;
var hot = [];
var activity = [];
var healthyinfo = [];

var lwidth = Dimensions.get('window').width-20;
var _this;
class TabFind extends Component {
	constructor(props) {  
		super(props);
		_navigator = this.props.navigator;
		var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      	this.state = {
        	hotdataSource: [],
        	activitydataSource: [],
        	healthyinfodataSource: [],
        	isRefreshing:false,
      	};
      	
      	this._onRefresh = this._onRefresh.bind(this);
      	
      	
  	}
	
	
	componentDidMount() {
//		net.postJson("http://api.idolly.com/m/articleapi/find"
//			,null
//			,this._netCallBack.bind(this)
//			,this._errorCallBack);
		this._articleRequest = this._articleRequest.bind(this);
		this._pressBtn = this._pressBtn.bind(this);
		this._renderItem = this._renderItem.bind(this);
		this._netCallBack = this._netCallBack.bind(this);
		this._errorCallBack = this._errorCallBack.bind(this);
		this._articleRequest();
	}
	
	async _articleRequest(){
		let formData = new FormData();  
		formData.append("phonenumber",this.state.username);  
		formData.append("password",this.state.password);
		var fetchOptions = {
          	method: 'POST',
          	headers: {     
          		'Accept': 'application/json',
          	},
          	body: formData
       	}; 
       	
		net.postFrom("http://www.idolly.com/article/index/articleBySort"
				,null
				,this._netCallBack 
				,this._errorCallBack);
	}
	
	_errorCallBack(data){
		_this = this;
      	
      	AsyncStorage.getItem("tabfind",function(errors,result){
			var json = eval('(' + result + ')');
			if(result != null){
				_this._netCallBack(json);
			}
			
		});
	}
	
	async _netCallBack(data){
		console.log(data);
		this.setState({hotdataSource: data.hot,
			activitydataSource:data.activity,
				healthyinfodataSource:data.healthyinfo});
				
		AsyncStorage.setItem('tabfind',JSON.stringify(data),function(errs){
            //TODO:错误处理
            if (errs) {
                console.log('存储错误');
            }
            if (!errs) {
                console.log('存储无误');
            }
        });
//		
//		this.setState({activitydataSource: findlist});
//		
//		this.setState({healthyinfodataSource: data.healthyinfodataSource});
	}
		
	JumptoList(){
		Alert.alert("1");
	}
	
	configureScenceAndroid(route) {
		return Navigator.SceneConfigs.FloatFromBottomAndroid;
	}

	_pressBtn(userid){
		var url = "http://www.idolly.com/article/index/articledetail?id="+userid;
		_navigator.push({id:"Web",url:url,articleid:userid});
	}
	
	_renderItem(data, i){
		console.log(data);
		return(
			<TouchableOpacity key={i} onPress={()=>this._pressBtn(data.id)}>
        		<View style={styles.item}>
				    <View style={styles.child}>
				    	<CacheableImage 
					        resizeMode="cover"
					        style={{height:Dimensions.get('window').width/2,width:Dimensions.get('window').width}}
					        source={{uri: data.image}}
					    />
				    </View>
			    </View>
		    </TouchableOpacity>
		);
	}
	
//	_renderRow(rowData, sectionID, rowID){
//		//console.log(rowData.image);
//      return (
//      	<TouchableOpacity onPress={()=>this._pressBtn(rowData.url)}>
//      		<View style={styles.Item}>
//				    <View style={styles.child}>
//				    	<Image style={styles.image} source={{uri: rowData.image}} />
//				    </View>
//			    </View>
//		    </TouchableOpacity>
//      );
//  }
	
	_onRefresh(){
		this.setState({isRefreshing:true});
		net.postJson("http://www.idolly.com/article/index/articleBySort"
			,null
			,this._netCallBack
			,this._errorCallBack);
		setTimeout(() => {
	      	this.setState({isRefreshing:false});
	    }, 1000);
	}
		/**
	 *配置跳转路由
	 */
	render() {
		let configureScence = this.configureScenceAndroid;
		let renderScene = this.renderSceneAndroid;
		
		this._onRefresh = this._onRefresh.bind(this);
	    return (
			<View style={styles.container} >
				<Header name='发现'/>
				<ScrollView style={styles.scrollview}
					refreshControl={
				        <RefreshControl
				            refreshing={this.state.isRefreshing}
				            onRefresh={this._onRefresh}
				            tintColor="#ff0000"
				            title="Loading..."
				            titleColor="#00ff00"
				            colors={['#ff0000', '#00ff00', '#0000ff']}
				            progressBackgroundColor="#ffff00"
				        />
			        }> 
			        <View style={styles1.pager}>
			        <View style={{height:10}}>
			        </View>
			       	<Grid
				        style={styles.item}
				        renderItem={this._renderItem}
				        data={this.state.hotdataSource}
				        itemsPerRow={1}
				    />
			       	<View style={styles1.line}>
			        	<Text style={styles1.findText}>活动</Text>
			        </View>
			        <Grid
				        style={styles.item}
				        renderItem={this._renderItem}
				        data={this.state.activitydataSource}
				        itemsPerRow={1}
				    />
			        <TouchableOpacity onPress={()=>_navigator.push({id:"MoreArticle",title:"活动",sort:"act"})}>
			        	<View style={styles1.button}>
			        		<Text style={styles1.findText}>查看更多</Text>
			        	</View>
			        </TouchableOpacity>
			        <View style={styles1.line}>
			        	<Text style={styles1.findText}>健康知识</Text>
			        </View> 
			        <Grid
				        style={styles.item} 
				        renderItem={this._renderItem}
				        data={this.state.healthyinfodataSource}
				        itemsPerRow={1}
				    />
			        <TouchableOpacity onPress={()=>_navigator.push({id:"MoreArticle",title:"健康知识",sort:"heal"})}>
			        	<View style={styles1.button}>
			        		<Text style={styles1.findText}>查看更多</Text>
			        	</View>
			        </TouchableOpacity>
			        </View>
				</ScrollView>
			</View>
	    );
	}
}

//<ListView 
//						dataSource={this.state.dataSource}
//		      			renderRow={this._renderRow.bind(this)}/>
const styles = StyleSheet.create({
  	container: {
    	flex: 1, 
    	justifyContent: 'center',
    	alignItems: 'center',
    	backgroundColor: '#FAF4FF',
  	},
  	welcome: {
    	fontSize: 20,
    	textAlign: 'center',
    	margin: 10,
  	},
  	instructions: {
    	textAlign: 'center',
    	color: '#333333',
    	marginBottom: 5,
  	},
    scrollview: {  
	    flex: 1,  
	   	width:Dimensions.get('window').width,
	},
	Item:{
		width:Dimensions.get('window').width,
		height:140,
	},
	child:{
		width:Dimensions.get('window').width,
		height:100,
		alignItems: 'center',
    	justifyContent: 'center',
	}, 
	image:{
		width:lwidth,
		height:lwidth/4*3,
		resizeMode:"contain",
	},
	item: {
	    flex: 1,
	    height: 160,
	    margin: 3
	},
	list: {
	    flex: 1
	},
});

module.exports = TabFind;
